package com.demo.dynamicProxy.demo01;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TakeOutFactory {

    private static TakeOutFactory takeOutFactory = new TakeOutFactory();

    private TakeOutFactory() {
    }

    public static TakeOutFactory getInstance() {
        return takeOutFactory;
    }

    /**
     *
     * @param obj
     * @return 返回的是代理对象，这个代理对象执行委托对象的方法时，都会转而执行invoke方法
     */
    public Object getJdkProxy(Object obj) {
        //这个obj是委托对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //proxy是代理对象
                System.out.println("手机下单");
                System.out.println("外卖员配送");
                //result是该方法执行后的返回值
                Object result = method.invoke(obj, args);
                System.out.println("亲给个五星好评");
                return result;
            }
        });
    }

    /**
     * cglib代理对于传入的Object 可以不用实现接口
     *
     * @param obj
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(), new net.sf.cglib.proxy.InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Object result = null;
                System.out.println("手机下单");
                System.out.println("外卖员配送");
                result = method.invoke(obj, objects);
                System.out.println("亲给个五星好评");
                return result;
            }
        });
    }
}
